import gettext
import locale
import os
from pathlib import Path


class I18nManager:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._init_translations()
        return cls._instance

    def _init_translations(self):
        self.locale_dir = Path(__file__).parent.parent / "i18n"
        self.languages = ["en_US", "zh_CN"]
        self.current_lang = "en_US"

        # 初始化系统语言
        sys_lang = locale.getdefaultlocale()[0]
        if sys_lang in self.languages:
            self.current_lang = sys_lang

        self._load_translation()

    def _load_translation(self):
        self.translation = gettext.translation(
            'messages',
            localedir=self.locale_dir,
            languages=[self.current_lang],
            fallback=True
        )
        self.translation.install()

    def set_language(self, lang_code):
        if lang_code in self.languages:
            self.current_lang = lang_code
            self._load_translation()

    def get_available_languages(self):
        return [
            (code, self._get_language_name(code))
            for code in self.languages
        ]

    def _get_language_name(self, code):
        return {
            "en_US": "English",
            "zh_CN": "简体中文"
        }.get(code, code)